﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using T.ServiceComponent.Kernel.Service;

namespace T.FAS.Runtime.MF.Runtime.Core
{
    internal class ConfigCenterService
    {
        public  string GetConfigValueFromConfigCenter(string configKey)
        {
            string isConfigCenterEnabled = ConfigurationManager.AppSettings["ConfigCenter.IsEnabled"];
            if (isConfigCenterEnabled != "1" && string.Equals("true", isConfigCenterEnabled, StringComparison.OrdinalIgnoreCase) == false)
            {
                return null;
            }

            string baseUriString = ConfigurationManager.AppSettings["ConfigCenter.Url"];
            if (string.IsNullOrEmpty(baseUriString) || string.IsNullOrEmpty(configKey))
            {
                return null;
            }

            //LocalLogger.Write($"获取到的租户ID为：{tenantId},configKey={configKey}", DateTime.Now);
            Uri uri = new Uri(new Uri(baseUriString), $"api/get?key={configKey.Trim()}");

            int Count = 3;
            while (Count >= 0)
            {
                try
                {
#if NET451
                    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
                    request.ContentType = "application/json";
                    request.Method = "Get";
                    request.Timeout = 10000;//10秒超时时间

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            string responseMsg = streamReader.ReadToEnd();
                            var jt = JObject.Parse(responseMsg);
                            if (jt["result_code"].ToString() == "0")
                            {
                                return jt["result_content"].ToString();
                            }
                            break;
                        }
                    }
#else
                    var client = HttpClientFactory.CreateClient();
                    var responseMsg = client.GetStringAsync(uri).Result;
                    var jt = JObject.Parse(responseMsg);
                    if (jt["result_code"].ToString() == "0")
                    {
                        return jt["result_content"].ToString();
                    }
                    break;
#endif
                }
                catch
                {
                    Count--;
                    if (Count <= 0)
                        throw;
                }
            }

            return null;
        }
    }
}
